<?php
/**
 * Created by PhpStorm.
 * User: Aaron
 * Date: 2019/5/20
 * Time: 11:54
 */

namespace Inter\Controller;

use Inter\Model\ConBannerModel;
use Inter\Model\GoodsModel;
use Inter\Model\GoodsCatModel;

class IndexController extends BaseController
{
//    private $auth = array('index', 'searchGood', 'treeGoodList');

    private $auth = array();

    // 鉴权
    public function __construct()
    {
        parent::__construct();
        if(in_array(ACTION_NAME, $this->auth)) {
            $bool = $this->requestAuth();
            if (!$bool){
                echo $this->_returnJson(array(),400,'授权错误'); exit;
            }
            $this->member_id = $bool;
        }
    }


    /**
     *  首页
     */
    public function index()
    {
       $data = array(
            'Banner'    => $this->getBanner(),
            'newGoods'  => $this->newGoods(),
            'tree'      => $this->_eachSub($this->getTree())
        );

       echo $this->_returnJson($data);
    }


    /**
     * 分类商品
     * @param $tree_id
     * @return mixed
     */
    public function treeGoodList($tree_id = '')
    {
        $gm = new GoodsModel();

        $tree_id = I('get.tree_id') == '' ? $tree_id : I('get.tree_id');
        $data = spellUrl($gm->treeList($tree_id), 'picture');

        if (!I('get.tree_id')) {
            return $data;
        }
        echo $this->_returnJson($data);
    }


    /**
     *  搜索商品
     */
    public function searchGood()
    {
        $name = I('get.name');
        $gm = new GoodsModel();
        echo $this->_returnJson($gm->searchGood($name));
    }


    /**
     * 返回轮播图
     * @return false|string
     */
    public function getBanner()
    {
        $cb   =  new ConBannerModel();
        $data = $cb->get_list('phone_index');
        return spellUrl($data, 'picture');
    }


    /**
     * 新品推荐
     * @return mixed
     */
    public function newGoods()
    {
        $gm   = new GoodsModel();
        $data = $gm->newList();
        return spellUrl($data, 'picture');
    }

    /**
     * 分类
     * @return array
     */
    public function getTree()
    {
        $gc   = new GoodsCatModel();
        $data = $gc->show_list();
        return spellUrl($data, 'adv_picture');
    }


    public function _eachSub($tree)
    {
        foreach ($tree as &$v) {
            if (isset($v['sub'][0])) {
                $subData = $this->treeGoodList($v['sub'][0]['cat_id']);
                if (is_null($subData)) {
                    $v['sub'][0]['subData'] = array();
                } else {
                    $v['sub'][0]['subData'] = $subData;
                }
            }
        }
        return $tree;
    }
}